﻿using EpubFactory.Robot.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EpubFactory.Robot.UI
{
    public partial class UpdateForm : Form
    {
        const string UpdateFile = "update.zip";
        Version currentVersion;
        public UpdateForm()
        {
            InitializeComponent();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ApplicationSetting.UpdateAgent) 
                || !File.Exists(ApplicationSetting.UpdateAgent))
            {
                MessageBox.Show("找不到更新程序");
                return;
            }
            Process.Start(ApplicationSetting.UpdateAgent);
            Environment.Exit(0);
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var client = new WebClient();
            bgWorker.ReportProgress(-1, "检测更新");
            var versionInfo = client.DownloadString(ApplicationSetting.UpdateUrl);
            if (!string.IsNullOrWhiteSpace(versionInfo))
            {
                var result = versionInfo.Split('\n');
                if (result.Length < 2)
                {
                    MessageBox.Show("检测版本出错");
                    return;
                }

                var version = new Version(result[0]);
                RunInMainthread(() =>
                {
                    this.lblLatestVersion.Text = version.ToString();
                });

                if (version > this.currentVersion)
                {
                    string url = null;
                    if (result.Length > 2)
                    {
                        url = result[2];
                    }
                    else
                    {
                        url = result[1];
                    }
                    bgWorker.ReportProgress(-1, "发现更新,开始下载");
                    client.DownloadFileAsync(new Uri(url), UpdateFile);
                    client.DownloadProgressChanged += client_DownloadProgressChanged;
                    client.DownloadFileCompleted += client_DownloadFileCompleted;
                }
            }
        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            btnUpdate.Enabled = true;
        }
        private void RunInMainthread(Action action)
        {
            if (IsHandleCreated)
            {
                this.BeginInvoke((Action)(delegate()
                {
                    if (action != null)
                    {
                        action.Invoke();
                    }
                }));
            }
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //bgWorker.ReportProgress(e.ProgressPercentage, "下载中");
            progressBar1.Value = e.ProgressPercentage;
        }

        private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage < 0)
            {
                statusInfo.Text = e.UserState.ToString();
            }
            else
            {
                progressBar1.Value = e.ProgressPercentage;
            }
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //btnUpdate.Enabled = true;
        }

        private void UpdateForm_Load(object sender, EventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            currentVersion = assembly.GetName().Version;
            lblCurrentVersion.Text = currentVersion.ToString();
            if (!bgWorker.IsBusy)
            {
                bgWorker.RunWorkerAsync();
            }
        }
    }
}
